package com.sunsys.QuestionAnswer;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.SessionCookieConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.jdbc.interceptors.SessionAssociationInterceptor;
import com.sunsys.QuestionAnswer.DBConnection;

//@WebServlet("/Post")
public class Post extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int qid=0;
		try {
			PrintWriter writer = response.getWriter();
			response.setContentType("text/html");
			PreparedStatement ps = null;
			ResultSet rs = null;
			
			DBConnection connection = new DBConnection();
			Connection con = connection.makeDBConnection();
			String sql = "insert into questions(QID,QNAME,PostedDate,UserID,ISAnswer) values(?,?,?,?,?)";
			String question = request.getParameter("question");
			ps = con.prepareStatement("select count(*) from questions");
			rs = ps.executeQuery();
			if(rs.next() == true)
			{
				qid = rs.getInt(1) + 1;
			}
			Date posteddate = new java.sql.Date(new java.util.Date().getTime());
			HttpSession session = request.getSession(true);
			Integer obj= (Integer)session.getAttribute("userId");
			int userId = obj.intValue();
			ps = con.prepareStatement(sql);
			ps.setInt(1, qid);
			ps.setString(2,question);
			ps.setDate(3, posteddate);
			ps.setInt(4,userId);
			ps.setString(5, "NO");
			int rows  = ps.executeUpdate();
			
			String username = (String)session.getAttribute("username");
			if(rows!=0 && userId!=0) {
				request.setAttribute("question", question);
				request.setAttribute("qid",qid);
				RequestDispatcher rd = request.getRequestDispatcher("QuestionPostSuccess.jsp");
				rd.forward(request, response);
			}
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
}
